import datetime
import uuid

from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from django.db.models import Q


def register(request):
    """用户注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，加到数据库。并且自动剔除那些在数据库中没有的字段，如 confirm_password,code
        # 用户表中新建一条数据（注册成功）
        instance = form.save()

        # 创建交易记录
        policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def sned_sms(request):
    """发送短信 """
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号不能为空，格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == "GET":
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 用户登录成功
        mobile_phone = form.cleaned_data['mobile_phone']  # 用户信息存入session中
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        # request.session['user_name'] = user_object.username
        request.session.set_expiry(60 * 60 * 24 * 14)  # 设置超时时间（2周）

        return JsonResponse({"status": True, 'data': '/index/'})
    return JsonResponse({"status": False, 'error': form.errors})


def login(request):
    """用户名登录"""
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            # 用户登陆成功
            request.session['user_id'] = user_object.id  # 将用户ID存入session中
            request.session.set_expiry(60 * 60 * 24 * 14)  # 设置超时时间（2周）

            return redirect('index')
        form.add_error("username", "用户名或密码错误！")
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成验证码"""
    from utils.code import check_code
    from io import BytesIO

    image_object, code = check_code()
    request.session['image_code'] = code
    # 设置图片验证码的存在时间
    request.session.set_expiry(60)

    stream = BytesIO()
    image_object.save(stream, 'png')
    # stream.getvalue()

    return HttpResponse(stream.getvalue())


def logout(request):
    """用户退出"""
    request.session.flush()  # 讲session中的数据清空一下
    return redirect('index')
